<?php
namespace App\Services;


use App\Models\Hall;
use App\Models\ReportPartnerGame;
use common\utils\SysCode;
use Illuminate\Support\Facades\DB;

class StatisticsService
{
    //第三方
    const REPORT_PARTNER_GAME_FORMAT_TYPE = [
        'FG' => ['timezone' => '美东时间', 'report_type' => '下注时间(捕鱼类为结算时间)'],
        'HB' => ['timezone' => '北京时间', 'report_type' => '结算时间'],
        'MW' => ['timezone' => '北京时间', 'report_type' => '下注时间'],
        'OG' => ['timezone' => '北京时间', 'report_type' => '下注时间'],
        'MG' => ['timezone' => '北京时间', 'report_type' => '下注时间'],
        'CQ9' => ['timezone' => '美东时间', 'report_type' => '下注时间'],
        'GNS' => ['timezone' => '美东时间', 'report_type' => '下注时间'],
        'SB' => ['timezone' => '美东时间', 'report_type' => '结算时间'],
        'HC' => ['timezone' => '北京时间', 'report_type' => '结算时间'],
        'BG' => ['timezone' => '美东时间', 'report_type' => '结算时间'],
        'KY' => ['timezone' => '北京时间', 'report_type' => '结算时间'],
        'LEG' => ['timezone' => '北京时间', 'report_type' => '结算时间'],
        'SG' => ['timezone' => '北京时间', 'report_type' => '下注时间'],
        'EBET' => ['timezone' => '北京时间', 'report_type' => '下注时间'],
        'LEBO' => ['timezone' => '美东时间', 'report_type' => '下注时间'],
    ];
    /**
     * 获取总报表数据
     * @param array $params [ company_name: 厅主名， company_account： 厅主账号， date_begin：投注结算时间起始， date_end 投注结算时间结束， page 分页码， page_size: 分页大小 ]
     * @return array
     */
    public static function getAllStatistics($params)
    {
        $hall_id = 0;
        // 厅主名和账号精确匹配
        if (isset($params['company_name']) || isset($params['company_account'])){
            $where = [];
            isset($params['company_name']) &&  $where = array_merge($where,['company_name' => $params['company_name']]);
            isset($params['company_account']) && $where = array_merge($where,['admin_name' => $params['company_account']]);
            $hall = Hall::where($where)->first();
            if(empty($hall)){
                error_exit(SysCode::HALL_NOT_EXISTS, ['reason'=> (isset($params['company_name']) ? '名称：'.$params['company_name']:''). (isset($params['company_account']) ? '账号：'.$params['company_account']:'') ]);
            }
            $hall_id = $hall->id;
        }
        $where = [];
        !empty($hall_id) && $where[] = ['hall_id', '=', $hall_id];
        isset($params['date_begin']) && $where[] = ['date', '>=', $params['date_begin']];
        isset($params['date_end']) && $where[] = ['date', '<=', $params['date_end']];// 23:59:59 需要 ‘=’
        $hall = Hall::select('id', 'company_name','admin_name as company_account');
        if(!empty($hall_id)){
            $hall->where(['id'=>$hall_id]);
        }
        $report = ReportPartnerGame::select(
            'hall_id as id', 'h.company_name','h.company_name',
            DB::raw('SUM(bet_amount) bet_amount'),//投注总额
            DB::raw('SUM(validbet) validbet'),// 总有效投注额
            DB::raw('SUM(validbet_times) bet_number'),// 有效注单数
            DB::raw('SUM(bonus_amount) bet_total_amount'),// 彩金额
            DB::raw('SUM(contribute_amount) contribute_amount'),// 贡献额
            DB::raw('SUM(profit) profit')// 会员输赢
        )->leftJoinSub($hall, 'h' , function($join) {
            $join->on('h.id', '=', 'report_partner_game.hall_id');
        })->where($where)->groupBy('hall_id');
        // 排序字段组装
        if (isset($params['order'])){
            empty($params['desc']) && $params['desc'] = 'desc';
            $report->orderBy($params['order'], $params['desc']);
        }
        $total = $report->get()->toArray();
        $data = get_page_data($report, $params['page'], $params['page_size']);
        // 获取总计数据
        $data['totalSum'] = [
            'bet_amount'=> !empty($total) ? array_sum(array_column($total, 'bet_amount')) : 0 ,
            'validbet'=> !empty($total) ? array_sum(array_column($total, 'validbet')) : 0 ,
            'bet_number'=> !empty($total) ? array_sum(array_column($total, 'bet_number')) : 0 ,
            'bet_total_amount'=> !empty($total) ? array_sum(array_column($total, 'bonus_amount')) : 0,
            'contribute_amount'=> !empty($total) ? array_sum(array_column($total, 'contribute_amount')) : 0,
            'profit'=> !empty($total) ? array_sum(array_column($total, 'profit')) : 0,
        ];
        // 获取分页数据小计
        $data['subTotalSum'] = [
            'bet_amount'=> !empty($data['list']) ? array_sum(array_column($data['list'], 'bet_amount')) : 0 ,
            'validbet'=> !empty($data['list']) ? array_sum(array_column($data['list'], 'validbet')) : 0 ,
            'bet_number'=> !empty($data['list']) ? array_sum(array_column($data['list'], 'bet_number')) : 0 ,
            'bet_total_amount'=> !empty($data['list']) ? array_sum(array_column($data['list'], 'bonus_amount')) : 0,
            'contribute_amount'=> !empty($data['list']) ? array_sum(array_column($data['list'], 'contribute_amount')) : 0,
            'profit'=> !empty($data['list']) ? array_sum(array_column($data['list'], 'profit')) : 0,
        ];
        return $data;
    }

    /**
     * @param $params [ company_name: 厅主名， games：游戏类型， date_begin：投注结算时间起始， date_end 投注结算时间结束， page 分页码， page_size: 分页大小 ]
     *  游戏类型 ： [{"partner_id":游戏id,"game_type":游戏类型}]
     * @return array
     */
    public static function getGameStatistics($params)
    {
        $hall_id = 0;
        // 厅主名精确匹配
        if (isset($params['company_name'])){
            $hall = Hall::where(['company_name' => $params['company_name']])->first();
            if(empty($hall)){
                error_exit(SysCode::HALL_NOT_EXISTS, ['reason'=> (isset($params['company_name']) ? '名称：'.$params['company_name']:''). (isset($params['company_account']) ? '账号：'.$params['company_account']:'') ]);
            }
            $hall_id = $hall->id;
        }
        $where = [];
        !empty($hall_id) && $where[] = ['hall_id', '=', $hall_id];
        isset($params['date_begin']) && $where[] = ['date', '>=', $params['date_begin']];
        isset($params['date_end']) && $where[] = ['date', '<=', $params['date_end']];// 23:59:59 需要 ‘=’
        $hall = Hall::select('id', 'company_name','admin_name as company_account');
        if(!empty($hall_id)){
            $hall->where(['id'=>$hall_id]);
        }

        //区分 系统游戏报表 和 第三方对账游戏报表
        if($params['type'] == 1){
            $model = 'App\Models\ReportPartnerGame';
            $alias = 'report_partner_game';
        }else{
            $model = 'App\Models\ReportPartnerGameThird';
            $alias = 'report_partner_game_third';
        }
        $report = $model::select(
            'hall_id',
            'h.company_name',
            'h.company_account',
            'partner_id',
            'partner_name',
            'game_type',
            DB::raw('SUM(bet_amount) bet_amount'),//投注总额
            DB::raw('SUM(validbet) validbet'),// 总有效投注额
            DB::raw('SUM(validbet_times) bet_number'),// 有效注单数
            DB::raw('SUM(bonus_amount) bet_total_amount'),// 彩金额
            DB::raw('SUM(contribute_amount) contribute_amount'),// 贡献额
            DB::raw('SUM(profit) profit')// 会员输赢
        )->leftJoinSub($hall, 'h' , function($join) use($alias) {
            $join->on('h.id', '=', $alias . '.hall_id');
        })->where($where);
        // 游戏类型
        if (isset($params['games'])){
            $games = json_decode ($params['games'],true);
            $gamesIdArray = array_column($games,'partner_id');
            $gameTypeArray = array_column($games,'game_type');
            $report->whereIn('partner_id',$gamesIdArray);
            $report->whereIn('game_type',$gameTypeArray);
        }
        $report = $report->groupBy('partner_id')->groupBy('game_type')->groupBy('hall_id');
        // 排序字段组装
        if (isset($params['order'])){
            empty($params['desc']) && $params['desc'] = 'desc';
            $report->orderBy($params['order'], $params['desc']);
        }
        $total = $report->get()->toArray();
        $data = get_page_data($report, $params['page'], $params['page_size']);
        //第三方对账报表增加字段： 时间类型， api统计时间
        if(!empty($data['list']) && $params['type'] == 2){
            foreach ($data['list'] as & $val){
                $val = (array)$val;
                $val['timezone'] = isset(self::REPORT_PARTNER_GAME_FORMAT_TYPE[$val['partner_name']]) ? self::REPORT_PARTNER_GAME_FORMAT_TYPE[$val['partner_name']]['timezone'] : '美东时间';//美东时间 世界标准时间 北京时间
                $val['report_type'] = isset(self::REPORT_PARTNER_GAME_FORMAT_TYPE[$val['partner_name']]) ? self::REPORT_PARTNER_GAME_FORMAT_TYPE[$val['partner_name']]['report_type'] : '下注时间';//下注时间， 结算时间
            }
        }
        // 获取总计数据
        $data['totalSum'] = [
            'bet_amount'=> !empty($total) ? array_sum(array_column($total, 'bet_amount')) : 0 ,
            'validbet'=> !empty($total) ? array_sum(array_column($total, 'validbet')) : 0 ,
            'bet_number'=> !empty($total) ? array_sum(array_column($total, 'bet_number')) : 0 ,
            'bet_total_amount'=> !empty($total) ? array_sum(array_column($total, 'bonus_amount')) : 0,
            'contribute_amount'=> !empty($total) ? array_sum(array_column($total, 'contribute_amount')) : 0,
            'profit'=> !empty($total) ? array_sum(array_column($total, 'profit')) : 0,
        ];
        // 获取分页数据小计
        $data['subTotalSum'] = [
            'bet_amount'=> !empty($data['list']) ? array_sum(array_column($data['list'], 'bet_amount')) : 0 ,
            'validbet'=> !empty($data['list']) ? array_sum(array_column($data['list'], 'validbet')) : 0 ,
            'bet_number'=> !empty($data['list']) ? array_sum(array_column($data['list'], 'bet_number')) : 0 ,
            'bet_total_amount'=> !empty($data['list']) ? array_sum(array_column($data['list'], 'bonus_amount')) : 0,
            'contribute_amount'=> !empty($data['list']) ? array_sum(array_column($data['list'], 'contribute_amount')) : 0,
            'profit'=> !empty($data['list']) ? array_sum(array_column($data['list'], 'profit')) : 0,
        ];
        return $data;
    }

    /**
     * 总报表数据导出
     * @param array $params [ company_name: 厅主名， company_account： 厅主账号， date_begin：投注结算时间起始， date_end 投注结算时间结束， page 分页码， page_size: 分页大小 ]
     */
    public static function exportAllStatistics($params)
    {
        $data = static::getAllStatistics($params);
        amount_format_array($data, ['bet_amount', 'validbet','contribute_amount','bet_total_amount']);
        return $data;
    }
}